using System;
using System.Collections.Generic;
using System.IO;
using System.Linq.Expressions;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Threading;

namespace ExpressionSerialization
{
    public class NetTcpClient<TChannel> : ClientBase<TChannel>, IClient<TChannel> where TChannel : IQueryService
    {
        public NetTcpClient(Uri baseAddress, IEnumerable<Type> @knownTypes = null)
            : base(baseAddress, @knownTypes)
        {

		}


        public override object SynchronousCall(Expression<Func<TChannel, object>> methodcall, Type returnType)
        {
            object result = null;
            MethodCallExpression m = (MethodCallExpression)methodcall.Body;

            IEnumerable<Type> baseTypes = TypeResolver.GetBaseTypes(returnType);
            foreach (var b in baseTypes)
                this._knownTypes.Add(b);
            dynamic parameters = GetParameters(m);

            //GetOperationInfo(m.Method, BaseAddress, out method, out webattribute, out operationcontract, out requestformat, out responseformat);

            //ManualResetEvent reset = new ManualResetEvent(false);

            var chanel = ChannelFactory<IQueryService>.CreateChannel(GetNetTcpBinding(), new EndpointAddress(BaseAddress));
                result = m.Method.Invoke(chanel, new object[] {parameters});
            return result;
        }



        private static NetTcpBinding GetNetTcpBinding()
        {
            return new NetTcpBinding
            {
                Security = new NetTcpSecurity
                {
                    Mode = SecurityMode.None
                }
                ,
                MaxBufferPoolSize = 2147483647,
                MaxBufferSize = 2147483647,
                MaxReceivedMessageSize = 2147483647,
                ReaderQuotas =
                {
                    MaxArrayLength = 800000000,
                    MaxStringContentLength = 10000000,
                    MaxBytesPerRead = 4096000,
                    MaxDepth = 40000000
                }
            };
        }

    }
}